import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo02_DriverManager {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        //定义MySQL数据源对象
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8" +
                "&allowPublicKeyRetrieval=true&useSSL=false");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        //定义jdbc数据源对象
        DataSource dataSource=mysqlDataSource;
        try {
            connection=dataSource.getConnection();
            String sql="select student_id,sn,sname,mail,class_id from student where name=?";//?为占位符
            statement=connection.prepareStatement(sql);

            //下面用真实值绑定占位符
            System.out.println("请输入学生姓名");
            Scanner scanner=new Scanner(System.in);
            String name=scanner.next();
            statement.setString(1,name);//编号从1开始，有多少个值就多少个值

            resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                //bigint==long=8bytes
                long student_id = resultSet.getLong(1);
                String sn = resultSet.getString(2);
                String sname = resultSet.getString(3);
                String mail = resultSet.getString(4);
                long class_id = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0}，，学号={1}，学生姓名={2}，邮箱={3}，班级编号={4}",student_id,sn,sname,mail,class_id));
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //依次释放资源，关闭连接
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

